package com.ykt.controller;

import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.token.TokenManager;
import com.ykt.common.utils.StringUtil;
import com.ykt.model.Admin;
import com.ykt.model.Goods;
import com.ykt.model.GoodsRecommend;
import com.ykt.model.GoodsUnit;
import com.ykt.model.MediaSource;
import com.ykt.model.MediaSource.BizSubType;
import com.ykt.model.MediaSource.BizType;
import com.ykt.model.Shop;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@ControllerBind(controllerKey="/goods")
public class GoodsController extends BaseController<Goods>{
	
	public GoodsController(){
		super(Goods.class);
	}
	
	@Override
	public void grid() {
        int page = getParaToInt("page", 1);
        int rows = this.getParaToInt("rows", 20);
        
        Admin admin = getCurrentUser();
        Map<String, String> params = this.toParaMap();
        if(admin.get(Admin.role_ids)!=null && admin.getStr(Admin.role_ids).equals("6")){
        	params.put("EQ_s.id",admin.getInt(Admin.shopId).toString());
        }
        
        try {
            Page<Goods> data = Goods.dao.pageFindModel(page, rows, params);
            rendDataGrid(data);
        } catch (Exception e) {
            log.error(e);
            rendJson(false, e.getMessage());
        }
    }
	
	@Override
	public void edit() {
        try {
            Long id = this.getParaToLong(0, 0L);
            if (id != 0L) {
                po = get(id);
                if(po.get("unit_id")!=null){
                	GoodsUnit guPo = GoodsUnit.dao.findById(po.getInt("unit_id"));
                	this.setAttr("guPo", guPo);
                }
                String sql = "select * from media_source where  biz_type='GOODS' and biz_sub_type='GOODS_HEAD' and biz_id=? and status=1 order by sort";
                List<MediaSource> goodHeadMediaList = MediaSource.dao.find(sql,id);
                this.setAttr("goodHeadMediaList", goodHeadMediaList);
            } else {
                setAttr("now", new Date());
            }
            TokenManager.createToken(this, tokenName, tokenTout);
            this.setAttr("po", po);
        } catch (Exception e) {
            log.error("编辑异常", e);
        }
    }
	
	@Override
    public void save() {
        String msg = "";
        try {
            Model<Goods> m = this.getModel(Goods.class);
            
            Model<GoodsUnit> gu = this.getModel(GoodsUnit.class);

            Integer id = m.getInt("id");
            Long tokenl = this.getParaToLong("token");
            if (tokenl != null) {
                if (!TokenManager.validateToken(this, tokenName)) {
                    this.rendJson(false, "会话令牌错误！", id, new Random().nextLong());
                    return;
                }
            }
            
            String goodsNo = "";
    		int sgCatId = m.getInt("sg_cat_id");
            int shopId = m.getInt("shop_id");
    		String sgCatIdStr = StringUtil.lpad(2, sgCatId);
            String shopIdStr =  StringUtil.lpad(3, shopId);
            String timestamp = String.valueOf(System.currentTimeMillis());
            
            goodsNo = sgCatIdStr + shopIdStr + timestamp.substring(timestamp.length()-4, timestamp.length());

            Date now = new Date();
            if (id != null && id != 0) {
            	
            	if(StrKit.isBlank(m.getStr("goods_no"))){
                    m.set("goods_no", goodsNo);
            	}
            	
            	if(gu.get("id")!=null && !gu.get("id").equals("0")){
            		gu.set("updated_time", now);//修改时间
            		gu.update();
            	}
            	
                msg = "修改成功！";
                m.set("updated_time", now);//修改时间
                otherSave(m);
                m.update();
            } else {
                msg = "保存成功！";
                
//                String goodsNo = "";
//                int sgCatId = m.getInt("sg_cat_id");
//                int shopId = m.getInt("shop_id");
//                
//                String sgCatIdStr = StringUtil.lpad(2, sgCatId);
//                String shopIdStr =  StringUtil.lpad(3, shopId);
//                String timestamp = String.valueOf(System.currentTimeMillis());
//                goodsNo = sgCatIdStr + shopIdStr + timestamp.substring(timestamp.length()-4, timestamp.length());
                m.set("goods_no", goodsNo);
                
                Shop shop = Shop.dao.findById(shopId);
                m.set("market_id", shop.getInt("market_id"));
                
                if(gu != null){
                	gu.set("status", 1);
                	gu.set("created_time", now);//创建时间
                	gu.set("updated_time", now);//修改时间
                	gu.save();
                	
                	m.set("unit_id", gu.getInt("id"));
                }
                
                m.set("created_time", now);//创建时间
                m.set("updated_time", now);//修改时间
                m.save();
                otherSave(m);
            }

            id = m.getInt("id");
            rendJson(true, msg, id, new Random().nextLong());
        } catch (Exception e) {
            log.error("保存异常", e);
            rendJson(false, "保存异常！");
            e.printStackTrace();
        }
    }
	
	@Override
	protected void otherSave(Model<Goods> m) {
		//Product.dao.deleteAllPic(m.getInt("id"));//先删除所有
		MediaSource.dao.deleteMediaSource(m.getInt("id"), BizType.GOODS, BizSubType.GOODS_HEAD);//先删除相关媒体
		
		String[] medias = this.getParaValues("medias");
		Date time = new Date();
		int sort=0;
		if(medias==null||medias.length<1) {
			m.set("icon",null);
			return;
		}
		for(String mediaUrl : medias){
			Map<String,Object>map = new HashMap<String,Object>();
			map.put("biz_id", m.get("id") );
			map.put("biz_type", "GOODS");
			map.put("biz_sub_type", "GOODS_HEAD");
			map.put("media_type","IMAGE");
			map.put("cover", mediaUrl );
			map.put("content", mediaUrl );
			map.put("sort", sort++ );
			map.put("status",1);
			map.put("created_time", time );
			map.put("updated_time", time );
			new MediaSource().setAttrs(map).save();
		}
		m.set("icon", medias[0]);//最后一张图片设置为商品的默认图片
		m.update();
	}
	
	//批量上架/下架，修改商品状态
	public void batchOperator() {
		try {
			String ids = this.getPara("ids");
			String status = this.getPara("status");
			String msg = "上架成功！";
			if(status.equals("OUT")){
				msg = "下架成功！";
			}
			Db.update("update goods set updated_time=NOW(), status='"+status+"' where id in (" + ids + ")");
			rendJson(true, msg);
			
        } catch (Exception e) {
            log.error("上下架操作异常", e);
            rendJson(false, "操作异常！");
        }
    }
	
	//批量推荐
	public void batchRecommend() {
		try {
			String ids = this.getPara("ids");
			String recommendType = this.getPara("recommendType");
			String msg = "首页推荐成功！";

			Date date = new Date();
			if(recommendType.equals("APP")){
				String[] idsArray = ids.split(",");
				int idsSize = idsArray.length;
				List<GoodsRecommend> appIndexList = GoodsRecommend.dao.find("select * from goods_recommend where type=?", "APP_INDEX");
				int hasRecommend = appIndexList.size();
				if((idsSize + hasRecommend)>8){
					msg = "已推荐"+hasRecommend+"个商品，首页推荐不能超过8个！";
					rendJson(false, msg);
				}else{
					
					for(String idStr : idsArray){
						int goodsId = Integer.valueOf(idStr);
						boolean flag = true;
						for(GoodsRecommend goodsRecommend : appIndexList){
							if(goodsRecommend.getInt(GoodsRecommend.goods_id) == goodsId){
								flag = false;
								break;
							}
						}
						if(flag){
							Goods g = Goods.dao.findByGoodsId(goodsId);
							GoodsRecommend gr = new GoodsRecommend();
//							gr.set(GoodsRecommend.marketId, g.getInt("market_id"));
//							gr.set(GoodsRecommend.shopId, g.getInt("shop_id"));
							gr.set(GoodsRecommend.biz_id, g.getInt("market_id"));
							gr.set(GoodsRecommend.goods_id, goodsId);
							gr.set(GoodsRecommend.type, "APP_INDEX");
							gr.set(GoodsRecommend.created_time, date);
							gr.set(GoodsRecommend.updated_time, date);
							gr.save();
						}
					}
					
					rendJson(true, msg);
				}
			}else if(recommendType.equals("SHOP")){
				String[] idsArray = ids.split(",");
				
				List<GoodsRecommend> appIndexList = GoodsRecommend.dao.find("select * from goods_recommend where type=?", "SHOP_INDEX");
				
				for(String idStr : idsArray){
					int goodsId = Integer.valueOf(idStr);
					
					boolean flag = true;
					for(GoodsRecommend goodsRecommend : appIndexList){
						if(goodsRecommend.getInt(GoodsRecommend.goods_id) == goodsId){
							flag = false;
							break;
						}
					}
					if(flag){
						Goods g = Goods.dao.findByGoodsId(goodsId);
						GoodsRecommend gr = new GoodsRecommend();
//						gr.set(GoodsRecommend.marketId, g.getInt("market_id"));
//						gr.set(GoodsRecommend.shopId, g.getInt("shop_id"));
						gr.set(GoodsRecommend.biz_id, g.getInt("shop_id"));
						gr.set(GoodsRecommend.goods_id, goodsId);
						gr.set(GoodsRecommend.type, "SHOP_INDEX");
						gr.set(GoodsRecommend.created_time, date);
						gr.set(GoodsRecommend.updated_time, date);
						gr.save();
					}
				}
				
				msg = "商铺详情页推荐成功！";
				rendJson(true, msg);
			}
			
        } catch (Exception e) {
            log.error("推荐操作异常", e);
            rendJson(false, "操作异常！");
        }
    }
	
	
	/**
	 * 取消推荐
	 */
	public void cancelRecommend() {
		String msg = "取消成功！";
		try {
			int goodsId = getParaToInt(0);
			String recommendType = getPara(1);
			
			//Goods g = Goods.dao.findByGoodsId(goodsId);
			String sql = "DELETE FROM goods_recommend WHERE goods_id=? and `type`=? ";	
			Db.update(sql, goodsId, recommendType);
			
			rendJson(true, msg, goodsId, new Random().nextLong());
		} catch (Exception e) {
			log.error("取消异常", e);
			rendJson(false, "取消异常！");
			e.printStackTrace();
		}
	}
}
